/**
 *  This file is part of OhSnap.
 *
 * 	Copyright (c) 2009 Gabriel Mendonça and Marcelo Machado
 * 
 *  OhSnap is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  OhSnap is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with OhSnap.  If not, see <http://www.gnu.org/licenses/>.
 *  
 */
package br.mm.cg;

import processing.core.PApplet;
import processing.core.PGraphics;
import processing.core.PVector;

/**
 * Represents a camera for a Processing application.
 * 
 * @author mendonça
 */
public class Camera {

	public static final boolean LEFT = false;
	public static final boolean RIGHT = true;
	
	public PApplet parent;
	public PVector position;
	public PVector aim;
	public PVector up;
	public float fovy;
	public float aspect;
	public float near;
	public float far;
	private boolean stereo3d;
	private boolean eye;

	public Camera(PApplet parent, boolean stereo3d) {
		float x, y, z;

		this.parent = parent;
		this.stereo3d = stereo3d;
		
		x = parent.width / 2.0f;
		y = parent.height / 2.0f;
		z = y / PApplet.tan(PApplet.PI * 60.0f / 360.0f);

		this.position = new PVector(x, y, z);
		this.aim = new PVector(x, y, 0.0f);
		this.up = new PVector(0.0f, 1.0f, 0.0f);

		// Perspective
		this.fovy = PApplet.PI / 3.0f;
		this.near = z / 100.0f;
		this.far = z * 10.0f;

		if (stereo3d) {
			this.aspect = (float) parent.width / 2.0f / parent.height;
			this.eye = LEFT;
		} else {
			this.aspect = (float) parent.width / parent.height;
		}
	}

	public void setUp(PGraphics pGraphics) {
		pGraphics.perspective(fovy, aspect, near, far);
		
		if (stereo3d) {
			//  --------------------/------RIGHT-----/---/-------LEFT------/
			float deviation = eye ? position.z * 0.04f : -position.z * 0.04f;
			eye = !eye;
			pGraphics.camera(position.x + deviation, position.y, position.z, aim.x, aim.y, aim.z,
					up.x, up.y, up.z);
		} else {
			pGraphics.camera(position.x, position.y, position.z, aim.x, aim.y, aim.z,
					up.x, up.y, up.z);
		}
	}
}
